import { useCallback, useEffect, useState, useRef } from 'react'
import { produce } from 'immer'
import useVarList from '../../_base/hooks/use-var-list'
import useOutputVarList from '../../_base/hooks/use-output-var-list'
import { BlockEnum, VarType } from '../../../types'
import type { ValueSelector, Var, Variable } from '../../../types'
import { useStore } from '../../../store'
import type { SpeechGeneratorNodeType, OutputVar, PromptSpeechType, PromptSpeechTemplateValue } from './types'
import useNodeCrud from '@/components/workflow/nodes/_base/hooks/use-node-crud'
import useOneStepRun from '@/components/workflow/nodes/_base/hooks/use-one-step-run'
import { fetchNodeDefault } from '@/services/workflow'
import { useStore as useAppStore } from '@/components/app/store'
import {
  useNodesReadOnly,
} from '@/components/workflow/hooks'
import { useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/components/header/account-setting/model-provider-page/hooks'
import { ModelTypeEnum } from '@/components/header/account-setting/model-provider-page/declarations'
import { ModelModeType } from '@/services/types/app'

const useConfig = (id: string, payload: SpeechGeneratorNodeType) => {
  const { nodesReadOnly: readOnly } = useNodesReadOnly()
  const appId = useAppStore.getState().appDetail?.id

  const defaultConfig = useStore(s => s.nodesDefaultConfigs)[payload.type]
  const { inputs, setInputs } = useNodeCrud<SpeechGeneratorNodeType>(id, payload)
  const { handleVarListChange, handleAddVariable } = useVarList<SpeechGeneratorNodeType>({
    inputs,
    setInputs,
  })
  const inputRef = useRef(inputs)
  const model = inputs.model
  const [modelChanged, setModelChanged] = useState(false)
  const {
    currentProvider,
    currentModel,
  } = useModelListAndDefaultModelAndCurrentProviderAndModel(ModelTypeEnum.tts)

  const [outputKeyOrders, setOutputKeyOrders] = useState<string[]>([])
  const syncOutputKeyOrders = useCallback((outputs: OutputVar) => {
    setOutputKeyOrders(Object.keys(outputs))
  }, [])

  const handleModelChanged = useCallback((model: { provider: string; modelId: string; mode?: ModelModeType }) => {
    const newInputs = produce(inputRef.current, (draft) => {
      draft.model.provider = model.provider
      draft.model.name = model.modelId
      draft.model.mode = model.mode!
    })
    setInputs(newInputs)
    setModelChanged(true)
  }, [setInputs, defaultConfig])

  useEffect(() => {
    if (currentProvider?.provider && currentModel?.model && !model.provider) {
      handleModelChanged({
        provider: currentProvider?.provider,
        modelId: currentModel?.model,
        mode: currentModel?.model_properties?.mode as ModelModeType,
      })
    }
  }, [model.provider, currentProvider, currentModel, handleModelChanged])

  useEffect(() => {
    if (inputs.text) {
      return
    }

    const isReady = defaultConfig && Object.keys(defaultConfig).length > 0
    if (isReady) {
      setInputs({
        ...inputs,
        ...defaultConfig,
      })
      syncOutputKeyOrders(defaultConfig.outputs)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [defaultConfig])

  const handleTextChange = useCallback((text: string) => {
    const newInputs = produce(inputs, (draft) => {
      draft.text = text
    })
    setInputs(newInputs)
  }, [inputs, setInputs])

  const handlePromptSpeechChange = useCallback((prompt_text: string, prompt_speech: string) => {
    const newInputs = produce(inputs, (draft) => {
      draft.prompt_speech = {
        prompt_text,
        prompt_speech
      }
    })
    setInputs(newInputs)
  }, [inputs, setInputs])

  const handlePromptSpeechTemplateChange = useCallback((gender: '男' | '女', template: string) => {
    const newInputs = produce(inputs, (draft) => {
      draft.prompt_speech_template = {
        gender,
        template
      }
    })
    setInputs(newInputs)
  }, [inputs, setInputs])

  const handlePromptSpeechSelectorChange = useCallback((prompt_speech_selector: ValueSelector,
    prompt_text_selector: ValueSelector) => {
    const newInputs = produce(inputs, (draft) => {
      draft.prompt_speech_selector = {
        prompt_speech_selector,
        prompt_text_selector
      }
    })
    setInputs(newInputs)
  }, [inputs, setInputs])

  const handlePromptSpeechType = useCallback((prompt_speech_type: PromptSpeechType) => {
    const newInputs = produce(inputs, (draft) => {
      draft.prompt_speech_type = prompt_speech_type
    })
    setInputs(newInputs)
  }, [inputs, setInputs])

  const handlePromptSpeechTemplate = useCallback((prompt_speech_template: PromptSpeechTemplateValue) => {
    const newInputs = produce(inputs, (draft) => {
      draft.prompt_speech_template = prompt_speech_template
    })
    setInputs(newInputs)
  }, [inputs, setInputs])

  const handleCompletionParamsChange = useCallback((newParams: Record<string, any>) => {
    // const newInputs = produce(inputs, (draft) => {
    //   draft.model.completion_params = newParams
    // })
    // setInputs(newInputs)
  }, [inputs, setInputs])

  const {
    handleVarsChange,
    handleAddVariable: handleAddOutputVariable,
    handleRemoveVariable,
    isShowRemoveVarConfirm,
    hideRemoveVarConfirm,
    onRemoveVarConfirm,
  } = useOutputVarList<SpeechGeneratorNodeType>({
    id,
    inputs,
    setInputs,
    outputKeyOrders,
    onOutputKeyOrdersChange: setOutputKeyOrders,
  })

  const filterVar = useCallback((varPayload: Var) => {
    return [VarType.string, VarType.number, VarType.secret, VarType.object, VarType.array, VarType.arrayNumber, VarType.arrayString, VarType.arrayObject].includes(varPayload.type)
  }, [])

  // single run
  const {
    isShowSingleRun,
    hideSingleRun,
    toVarInputs,
    runningStatus,
    isCompleted,
    handleRun,
    handleStop,
    runInputData,
    setRunInputData,
    runResult,
  } = useOneStepRun<SpeechGeneratorNodeType>({
    id,
    data: inputs,
    defaultRunInputData: {},
  })

  return {
    readOnly,
    inputs,
    outputKeyOrders,
    handleVarListChange,
    handleAddVariable,
    handleRemoveVariable,
    handleModelChanged,
    handleCompletionParamsChange,
    handleTextChange,
    handlePromptSpeechChange,
    handlePromptSpeechTemplateChange,
    handlePromptSpeechSelectorChange,
    handlePromptSpeechType,
    handlePromptSpeechTemplate,
    handleVarsChange,
    filterVar,
    handleAddOutputVariable,
    isShowRemoveVarConfirm,
    hideRemoveVarConfirm,
    onRemoveVarConfirm,
    // single run
    isShowSingleRun,
    hideSingleRun,
    runningStatus,
    isCompleted,
    handleRun,
    handleStop,
    runResult,
  }
}

export default useConfig
